package ldh.maker.component;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.AnchorPane;
import ldh.maker.db.SettingDb;
import ldh.maker.util.ConnectionFactory;
import ldh.maker.util.DialogUtil;
import ldh.maker.vo.DBConnectionData;
import ldh.maker.vo.SettingData;
import ldh.maker.vo.SettingJson;
import ldh.maker.vo.TreeNode;
import org.controlsfx.validation.Severity;
import org.controlsfx.validation.ValidationSupport;
import org.controlsfx.validation.Validator;

import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;

/**
 * Created by ldh on 2017/3/25.
 */
public class PackagePane extends AnchorPane {
    ValidationSupport validationSupport = new ValidationSupport();

    protected TreeItem<TreeNode> treeItem;
    protected String dbName;

    @FXML
    TextField xmlPackageField;
    @FXML
    TextField pojoPackageField;
    @FXML
    TextField daoPackageField;
    @FXML
    TextField servicePackageField;
    @FXML
    TextField controllerPackageField;
    @FXML
    CheckBox serverInterfaceCheckBox;
    @FXML
    CheckBox lombokCheckBox;
    @FXML CheckBox shiroCheckBox;
    @FXML CheckBox crossDomainCheckBox;

    protected boolean isSetting = false;

    public PackagePane(TreeItem<TreeNode> treeItem, String dbName) {
        this.treeItem = treeItem;
        this.dbName = dbName;
        initUi();
    }

    protected void initUi() {
        try {
            FXMLLoader fxmlLoader = new FXMLLoader(PackagePane.class.getResource("/fxml/SettingPaneForm.fxml"));
            fxmlLoader.setRoot(this);
            fxmlLoader.setController(this);
            fxmlLoader.load();
            initialize(null, null);
            serverInterfaceCheckBox.setSelected(true);
            loadData(treeItem);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void loadData(TreeItem<TreeNode> treeItem) {
        try {
            SettingData data = SettingDb.loadData(treeItem.getParent().getValue(), dbName);
            if (data == null)return;
            xmlPackageField.setText(data.getXmlPackageProperty());
            pojoPackageField.setText(data.getPojoPackageProperty());
            daoPackageField.setText(data.getDaoPackageProperty());
            servicePackageField.setText(data.getServicePackageProperty());
            controllerPackageField.setText(data.getControllerPackageProperty());
            serverInterfaceCheckBox.setSelected(data.getServiceInterface());
            SettingJson settingJson = data.getSettingJson();
            if (settingJson != null) {
                lombokCheckBox.setSelected(settingJson.isLombok());
                shiroCheckBox.setSelected(settingJson.isShiro());
                crossDomainCheckBox.setSelected(settingJson.isCrossDomain());
            } else {
                lombokCheckBox.setSelected(false);
                shiroCheckBox.setSelected(false);
                crossDomainCheckBox.setSelected(false);
            }
            isSetting = true;
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @FXML
    public void saveBtn() throws SQLException {
        if(validationSupport.isInvalid()) {
            DialogUtil.show(Alert.AlertType.WARNING, "填写错误", "请按照要求填写");
            return;
        }
        SettingData settingData = buildSettingData();
        DBConnectionData data = (DBConnectionData) treeItem.getValue().getParent().getData();
        Connection connection = data.getConnection();
        if (connection == null) {
            connection = ConnectionFactory.getConnection(data);
            data.setConnection(connection);
        }
        if (connection == null) {
            DialogUtil.show(Alert.AlertType.WARNING, "填写错误", "数据库连接不上");
            return;
        }
        SettingData data2 = SettingDb.loadData(treeItem.getParent().getValue(), dbName);
        settingData.setDbName(dbName);
        if (data2 == null) {
            SettingDb.save(settingData, treeItem.getParent().getValue());
        } else {
            SettingDb.update(settingData, treeItem.getParent().getValue());
        }
        DialogUtil.show(Alert.AlertType.INFORMATION, "成功", "设置成功");
    }

    private SettingData buildSettingData() {
        SettingData settingData = new SettingData();
        settingData.setXmlPackageProperty(xmlPackageField.getText().trim());
        settingData.setPojoPackageProperty(pojoPackageField.getText().trim());
        settingData.setDaoPackageProperty(daoPackageField.getText().trim());
        settingData.setServicePackageProperty(servicePackageField.getText().trim());
        settingData.setControllerPackageProperty(controllerPackageField.getText());
        settingData.setServiceInterface(serverInterfaceCheckBox.isSelected());
        SettingJson settingJson = new SettingJson();
        settingJson.isLombok(lombokCheckBox.isSelected());
        settingJson.setShiro(shiroCheckBox.isSelected());
        settingJson.setCrossDomain(crossDomainCheckBox.isSelected());
        Gson gson = new Gson();
        settingData.setJson(gson.toJson(settingJson));
        return settingData;
    }

    public void initialize(URL location, ResourceBundle resources) {
        validationSupport.registerValidator(xmlPackageField, Validator.createEmptyValidator("mybatis的xml包路径不能为空"));
        validationSupport.registerValidator(pojoPackageField, Validator.createRegexValidator("POJO包路径不能为空", "^([a-zA-Z]+[.]{0,1})+$", Severity.ERROR));
        validationSupport.registerValidator(daoPackageField, Validator.createRegexValidator("DAO包路径不能为空", "^([a-zA-Z]+[.]{0,1})+$", Severity.ERROR));
        validationSupport.registerValidator(servicePackageField, Validator.createRegexValidator("SERVICE包路径不能为空", "^([a-zA-Z]+[.]{0,1})+$", Severity.ERROR));
        validationSupport.registerValidator(controllerPackageField, Validator.createRegexValidator("CONTROLLER包路径不能为空", "^([a-zA-Z]+[.]{0,1})+$", Severity.ERROR));
    }

    public boolean isSetting() {
        return isSetting;
    }
}
